import { GoodsAPI } from "@/api/GoodsAPI";
import type { Evaluate, EvaluateInfo, EvaluateRequestParams, Goods, GoodsDetailInfo, GoodsRequestParams } from "@/types/Goods";
import type { Pagination } from "@/types/Response";
import type { Status } from "@/types/Status"


import chunk from "lodash/chunk";

type State = {
    //商品信息
    goodsInfo: {
        status: Status;
        result: Goods;
    }
    //同类商品/猜你喜欢
    relevantGoods: {
        result: Goods[][]
        //加载状态
        status: Status;

    }
    //榜单
    hotSaleGoods: {
        //加载状态
        status: Status;
        //榜单数据
        result: {
            //24小时榜
            1: Goods[]
            //周榜
            2: Goods[]
            //总榜
            3: Goods[]

        }
    }
    //商品评价信息
    evaluateInfo: {
        //加载状态
        status: Status;
        //商品评价信息数据
        result: EvaluateInfo
    }
    //商品评价列表
    evaluateList: {
        //商品评价列表数据
        result: Pagination<Evaluate>,
        //加载状态
        status: Status;

    }
}

type Actions = {
    //根据商品id获取商品信息
    getGoodsInfo(id: string): Promise<void>;
    //更新商品信息（规格组合发生变化时）
    updateGoodsInfo(goods: Data): void
    //获取同类商品（猜你喜欢）
    getRelevantGoods(args?: { id?: string; limit?: number }): Promise<void>
    // 获取榜单
    getHotSaleGoods(id: string, type: 1 | 2 | 3, limit: number): Promise<void>;
    //获取商品评价信息
    getEvaluateInfo(id: string): Promise<void>;
    //获取商品列表
    getEvaluateList(id: string, reqParams: EvaluateRequestParams): Promise<void>
}

type Getters = {
    //获取商品图片
    mainPictures(): string[];
    //获取商品基本信息
    baseInfo(): Pick<Goods, "name" | "desc" | "price" | "oldPrice">
    //获取商品详细信息
    goodsProperties(): GoodsDetailInfo,


}

export const useGoodsStore = defineStore<"Goods", State, Getters, Actions>("Goods", {
    state: () => ({
        //商品信息
        goodsInfo: {
            status: 'idle',
            result: {
                id: "",
                name: "",
                desc: "",
                price: "",
                picture: "",
                discount: null,
                orderNum: null,
                spuCode: "",
                oldPrice: "",
                inventory: 0,
                brand: [],
                salesCount: 0,
                commentCount: 0,
                collectCount: 0,
                mainVideos: [],
                videoScale: 0,
                mainPictures: [],
                specs: [],
                skus: [],
                categories: [],
                details: {
                    pictures: [],
                    properties: [],
                },
                isPreSale: false,
                isCollect: false,
                userAddresses: null,
                similarProducts: [],
                hotByDay: [],
                evaluationInfo: null,
            }
        },
        //同类商品和猜你喜欢
        relevantGoods: {
            result: [],
            //加载状态
            status: 'idle',


        },
        //榜单
        hotSaleGoods: {
            result: {
                1: [],
                2: [],
                3: []
            },
            //加载状态
            status: 'idle',
        },
        //商品评价信息
        evaluateInfo: {
            //加载状态
            status: 'idle',
            result: {
                //购买人数
                salesCount: 0,
                //好评率
                praisePercent: "",
                //评价数量（总）
                evaluateCount: 0,
                //评价数量（有图）
                hasPictureCount: 0,
                //评价标签
                tags: []
            }
        },
        //商品评价列表
        evaluateList: {
            result: {
                page: 0,
                pages: 0,
                pageSize: 0,
                counts: 0,
                items: []

            },
            //加载状态
            status: 'idle'
        }

    }),
    actions: {
        //根据id获取商品信息
        async getGoodsInfo(id) {
            //更新加载状态
            this.goodsInfo.status = "loading";
            //捕获错误
            try {
                //发送请求，根据商品id获取商品详细信息
                let response = await GoodsAPI.getGoodsInfo(id);
                //存储商品详细信息
                this.goodsInfo.result = response.result;
                //更新加载状态
                this.goodsInfo.status = "success";

            } catch (e) {
                //更新加载状态
                this.goodsInfo.status = 'error'
            }
        },
        //更新商品信息（规格组合发生变化时）
        updateGoodsInfo(goods) {
            this.goodsInfo.result.price = goods.price
            this.goodsInfo.result.oldPrice = goods.oldPrice
            this.goodsInfo.result.inventory = goods.inventory
        },
        //获取同类商品信息
        async getRelevantGoods(args) {
            //更新加载状态
            this.relevantGoods.status = "loading";
            //捕获错误
            try {
                //发送请求，获取同类商品信息
                const response = await GoodsAPI.getRelevantGoods(args);
                //为商品分组，4个商品为一组
                this.relevantGoods.result = chunk(response.result, 4)
                //更新加载状态
                this.relevantGoods.status = "success"
            } catch (error) {
                //更新加载状态
                this.relevantGoods.status = "error"
            }
        },
        //获取榜单
        async getHotSaleGoods(id, type, limit) {
            //更新加载状态
            this.hotSaleGoods.status = "loading";
            //捕获错误
            try {
                // 发送请求获取榜单商品
                const response = await GoodsAPI.getHotSaleGoods(id, type, limit)
                //根据榜单类别存储榜单商品
                this.hotSaleGoods.result[type] = response.result
                //更新加载状态
                this.hotSaleGoods.status = "success"
            } catch (error) {
                //更新加载状态
                this.hotSaleGoods.status = "error"
            }
        },
        //获取评价头部信息
        async getEvaluateInfo(id) {
            //更新加载状态
            this.evaluateInfo.status = "loading"
            //捕获错误
            try {
                //发送请求获取商品评价信息
                const response = await GoodsAPI.getEvaluateInfo(id)
                //存储评价头部信息
                this.evaluateInfo.result = response.result
                //更新加载状态
                this.evaluateInfo.status = "success"
            } catch (e) {
                //更新加载状态
                this.evaluateInfo.status = "error"
            }
        },
        //获取评价列表
        async getEvaluateList(id, reqParams) {
            //更新加载状态
            this.evaluateList.status = "loading"
            //捕获错误
            try {
                //发送请求获取商品列表
                const response = await GoodsAPI.getEvaluateList(id, reqParams)
                //存储评价头部信息
                this.evaluateList.result = response.result
                //更新加载状态
                this.evaluateList.status = "success"
            } catch (e) {
                //更新加载状态
                this.evaluateList.status = "error"
            }
        }
    },
    getters: {
        //获取商品信息
        mainPictures() {
            return this.goodsInfo.result.mainPictures
        },
        //获取商品基本信息
        baseInfo() {
            const { name, desc, price, oldPrice } = this.goodsInfo.result;
            return {
                name, desc, price, oldPrice
            }
        },
        //获取商品详细信息
        goodsProperties() {
            return {
                //商品详细图片集合
                pictures: this.goodsInfo.result.details.pictures,
                //商品属性集合
                properties: this.goodsInfo.result.details.properties
            }
        }

    }

})

// 声明组件向外部传递的状态的类型规范
export interface Data {
    price: string;
    oldPrice: string;
    inventory: number;
    skuId: string;
}
